from django.shortcuts import redirect,render
from stuInfo.utils.pagination import Pagination
from stuInfo.models import Admin
from stuInfo.utils.bootstrap_modelForm import BootstrapModelForm
from django import forms
from django.core.exceptions import ValidationError

from stuInfo.utils.encrypt import md5
class AdminModelForm(BootstrapModelForm):
    confirm_password = forms.CharField(label='确认密码',max_length=32,widget=forms.PasswordInput(render_value=True))
    class Meta:
        model = Admin
        fields = "__all__"
        widgets={
            "password":forms.PasswordInput(render_value=True)
        }
    
    def clean_password(self):
        password = self.cleaned_data.get('password')
        return md5(password)

    def clean_confirm_password(self):
        confirm_password = md5(self.cleaned_data.get("confirm_password"))
        password = self.cleaned_data.get('password')
        if password == confirm_password:
            return confirm_password
        raise ValidationError('密码不一致')

        
        


def admin_index(request):
    queryset = Admin.objects.all()
    page_object = Pagination(request,queryset)
    page_queryset = page_object.page_queryset
    page_str = page_object.html()[0]
    page_info = page_object.html()[1]
    page_id_start = page_object.html()[2]
    
    dict = {
        "queryset": page_queryset,
        "page_str":page_str,
        "page_info": page_info,
        "page_id_start": page_id_start,
    }
    return render(request,"admin_index.html",dict)

def admin_add(request):
    if request.method == "GET":
        form = AdminModelForm()
        dict= {
            "form":form,
        }
        return render(request, "admin_change.html",dict)
    form = AdminModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect('/admin/index')
    return render(request,'admin_change.html',{
        "form":form,
    })